import axios from "axios";
import store from "@/store";
import router from "@/router";

const http = axios.create({
    baseURL: "/api",
    timeout: 3000,
    withCredentials:true
})

http.interceptors.request.use(config => {
    if (store.state.userStore.token) {
        config.headers["token"] = store.state.userStore.token
    }
    return config
}, err => {
    return err
})

http.interceptors.response.use(respone => {
    if (respone.data.token) {
        store.state.userStore.token = respone.data.token
    }
    errList[respone.data.code] && errList[respone.data.code]()
    return respone;
}, err => {
    console.log(err)
    if (err.message.indexOf("timeout") != -1 && err.code =="ECONNABORTED"){
        err.data={}
        err.data.msg="请求超时,请检查网络连接"
    }
    return err
})

const errList = {
    5007: () => router.replace({ path: "/login", query: { toPath: router.currentRoute.fullPath } }),
}

export default http